/**
 * [订单方法
 * @Author ljliu    2020-04-27T11:47:54+0800
 */
/* 1:正常(可开票，可退款)  2:退款中  3:已退款 4:开票中  5:已开票  6:已完成  7 退款失败  8开票失败   9不可退款可开票 10 可退款不可开票 */

function fnOrderStatusImg(val) {
    var orderStatusArr = [{
        "url": "../../image/order/refunding.png",
        "key": "2"
    }, {
        "url": "../../image/order/refunded.png",
        "key": "3"
    }, {
        "url": "../../image/order/invoicing.png",
        "key": "4"
    }, {
        "url": "../../image/order/invoiced.png",
        "key": "5"
    }, {
        "url": "../../image/order/complete.png",
        "key": "6"
    }, {
        "url": "../../image/order/refund_fail.png",
        "key": "7"
    }, {
        "url": "../../image/order/invoice_fail.png",
        "key": "8"
    }]
    for (var i = 0; i < orderStatusArr.length; i++) {
        if (orderStatusArr[i].key == val) {
            return orderStatusArr[i].url;
        }
    }
    return "";
}

// 获取订单状态文字
function fnOrderStatusText(orderStatus) {
    var orderStatusMap = {
        '12': '待付款', // 待付款
        '2': '待发货', // 待发货
        '3': '待收货', // 待收货
        '4': '已收货', // 已收货
        '5': '已完成', // 已完成
        '15': '已关闭', // 已关闭
        '20-1': '已取消', // 订单列表 - 退款、退款退货、换货 - 已取消
        '200': '待审核', // 订单列表 - 退款、退款退货、换货 - 待审核
        '201': '退货中', // 订单列表 - 退款、退款退货、换货 - 退货或退款中
        '202': '已完成', // 订单列表 - 退款、退款退货、换货 - 已完成 
        '203': '已拒绝', // 订单列表 - 退款、退款退货、换货 - 已拒绝 
        '204': '已通过', // 订单列表 - 退款、退款退货、换货 - 已通过
        '205': '买家已发货', // 订单列表 - 退款、退款退货、换货 - 买家已发货 
        '206': '卖家已发货', // 订单列表 - 退款、退款退货、换货 - 卖家已发货 
        '20_0': '换货', // 订单详情 - 订单售后状态
        '20_3': '退款退货', // 订单详情 - 订单售后状态 - 已取消该状态
        '20_1': '退款' // 订单详情 - 订单售后状态
    };
    return orderStatusMap[orderStatus+''] || '';
}

// 获取订单状态描述
function fnOrderStatusDesc(orderStatus) {
    var orderStatusDescMap = {
        '12': '剩余<span id="orderLeftTime"></span>自动关闭订单', // 待付款
        '2': '请耐心等待,将尽快为您安排发货', // 待发货
        '3': '订单已发货,请注意查收', // 待收货
        '4': '货物已送达', // 已收货
        '5': '货物已送达', // 已完成
        '15': '交易已关闭', // 已关闭
        '20-1': '已取消', // 订单详情 - 退款、退款退货、换货 - 已取消 
        '200': '待审核', // 订单详情 - 退款、退款退货、换货 - 待审核 
        '201': '退货中...', // 订单详情 - 退款、退款退货、换货 - 退货中
        '202': '已完成', // 订单详情 - 退款、退款退货、换货 - 已完成 
        '203': '已拒绝', // 订单详情 - 退款、退款退货、换货 - 已拒绝 
        '204': '已通过', // 订单详情 - 退款、退款退货、换货 - 已通过
        '205': '买家已发货', // 订单列表 - 退款、退款退货、换货 - 买家已发货 
        '206': '卖家已发货', // 订单列表 - 退款、退款退货、换货 - 卖家已发货 
    };
    return orderStatusDescMap[orderStatus] || '';
}

// 获取订单的按钮
// eventNames 为字符串是获取单个按钮，为数组获取按钮列表
// @return { name: '取消订单', eventName: 'cancle' }
function fnOrderStatusBtns(eventNames) {
    var btns = {
        'cancle': { name: '取消订单', eventName: 'cancle' },
        'pay': { name: '立即付款', eventName: 'pay', className: 'c-order-btn-highlight' },
        'logistics': { name: '查看物流', eventName: 'logistics' },
        'recieveGoods': { name: '确认收货', eventName: 'recieveGoods' },
        'sellService': { name: '申请售后', eventName: 'sellService' },
        'invoice': { name: '申请开票', eventName: 'invoice' },
        'buyAgain': { name: '再来一单', eventName: 'buyAgain' },
        'delete': { name: '删除订单', eventName: 'deteleOrder' },
        'cancelSellService': { name: '取消申请', eventName: 'cancelSellService' },
        'reInvoice': { name: '重开发票', eventName: 'reInvoice' },
        'comment': { name: '评价', eventName: 'comment' },
        'sendBack': { name: '输入物流信息', eventName: 'sendBack'},
        'shRecieveGoods': { name: '确认收货', eventName: 'shRecieveGoods' }
    };

    var result = [];
    if(typeof eventNames == 'string') {
        result = [btns[eventNames]];
    }else if(typeof eventNames == 'object') {
        for(var i = 0; i < eventNames.length; i ++) {
            result.push(btns[eventNames[i]])
        }
    }
    return result;
}

// 订单事件统一处理
var _actionBtn = null, _actionData = null, _actionIndex = -1;
function fnHandleOrderBtn(btn, data, index) {
    _actionBtn = btn;
    _actionData = data;
    _actionIndex = index;
    if(btn.eventName === 'cancle') {
        fnOrderAlert(12);
    } else if(btn.eventName === 'pay') {
        fnOrderPay(data);
    } else if(btn.eventName === 'logistics') {
        fnSeeLogistics(data);
    } else if(btn.eventName === 'recieveGoods') {
        fnOrderAlert(13);
    } else if(btn.eventName === 'sellService') {
        fnApplySellService(data);
    } else if(btn.eventName === 'invoice') {
        fnApplyInvoice(data);
    } else if(btn.eventName === 'buyAgain') {
        fnOrderBuyAgain(data);
    } else if(btn.eventName === 'deteleOrder') {
        fnOrderAlert(14);
    } else if(btn.eventName === 'cancelSellService') {
        fnOrderAlert(15);
    } else if(btn.eventName === 'reInvoice') {
        fnOrderReInvoice(data);
    } else if(btn.eventName === 'comment') {
        fnToComment(data);
    } else if(btn.eventName === 'sendBack') {
        fnOpenPublicWin('输入物流信息', 'teacher/transport_info', {
            id: _actionData.shId
        });
    } else if(btn.eventName === 'shRecieveGoods') {
        fnOrderAlert(25);
    }
    // 订单事件处理结果回调
    // status: true 成功 false 失败
    // event: 参考service-tools.js 834行
    // index: 列表上的第几个订单
    // orderEventCallback(status, event, index)
}

// 订单弹窗
function fnOrderAlert(type) {
    fnOpenAlert({
        alertType: type,
        alertConfirmFn: 'fnOrderAlertConfirm('+ type +')'
    });
}

// 订单弹窗回调
function fnOrderAlertConfirm(type) {
    var url = '',
        msg = ''; // 关闭交易
    var params = {
        // 订单 id
        orderId: _actionData.id
    };
    if(type == 14) {
        // 删除订单
        url = 'single/oms/deleteOrder';
        msg = '删除订单';
    }else if(type == 13) {
        // 确认收货
        url = 'single/oms/confimDelivery';
        msg = '确认收货';
        params.id = params.orderId;
        delete params.orderId;
    }else if(type == 15) {
        // 取消申请售后
        url = 'single/oms/order/aftersales/cancel';
        params.id = _actionData.id;
        msg = '取消申请';
    }else if(type == 12) {
        // 取消订单
        fnCancleOrder();
        return;
    }else if(type == 25) {
        // 换货-确认收货
        url = 'single/oms/userConfimReceive';
        params.id = _actionData.shId;
        msg = '确认收货';
    }
    
    var callback = function (data) {
        if(type == 14) {
            fnDeleteOrderMsg(params.orderId);
        }
        fnToast(msg);
        fnOrderActionCallback();
    };
    MALLPOST(url, params, callback);
}

// 订单删除后，删除订单消息
function fnDeleteOrderMsg(orderId) {
    var params = {
        orderId: orderId
    };
    var callback = function (data) {
        
    };
    MALLPOST('my/deleteMessageInfoByOrderId', params, callback);
}

function fnCancleOrder(id) {
    var url = 'payOrder/closeOrder',
        msg = '取消交易'; // 关闭交易
    var params = {
        // 订单 id
        orderId: id || _actionData.id
    };
    var callback = function (data) {
        fnToast(msg);
        fnOrderActionCallback();
    };
    POST(url, params, callback);
}


// 立即付款
function fnOrderPay(data) {
    // 接口缺失
    fnOpenPublicWin('支付详情', 'video/pay',{
        retData: {
            orderSn: data.orderSn,
            orderTotalAmount: data.payAmount,
            id: data.id
        },
        from: 3,
        refreshWin: api.winName,
        refreshFrm: api.frameName
    });
}

// 支付成功后的回调
function paySuccessCallback() {
    fnOrderActionCallback();
}

// 订单操作回调
function fnOrderActionCallback() {
    console.log(1 + '==================');
    orderEventCallback(true, _actionBtn.eventName, _actionIndex);
    _actionBtn = null;
    _actionData = null;
    _actionIndex = -1;
}

// 查看物流
function fnSeeLogistics(data) {
    fnOpenPublicWin('物流信息', 'teacher/transport', { orderId: data.id });
}

// 申请售后
function fnApplySellService(data) {
    // 接口缺失
    fnOpenPublicWin('选择售后商品', 'teacher/post_sale', {
        order: data,
        refreshWin: api.winName,
        refreshFrm: api.frameName
    });
}

// 申请开票
function fnApplyInvoice(data) {
    // 接口缺失
    fnOpenPublicWin('申请开票', 'teacher/invoice', {
        order: data,
        refreshWin: api.winName,
        refreshFrm: api.frameName
    });
}

// 再来一单
var _add_cart_id = [];
function fnOrderBuyAgain(data) {
    _add_cart_id = [];
    var callback = function() {
        var params = {
            'type': '2',
            'source': '2',
            'orderType': '1',
            'cartIds': _add_cart_id.join(','),
            'addressId': data.receiverId || ''
        };
        var _callback = function(res) {
            if(res) {
                delete res.memberReceiveAddressList;
                delete res.couponHistoryDetailList;
                delete res.basicGiftsList;
                res.address = {
                    name: res.address.name,
                    phone: res.address.phoneNumber,
                    schoolAddress: res.address.proviceName+res.address.cityName+res.address.regionName,
                    detailAddress: res.address.detailAddress,
                    id: res.address.id
                };
                params.orderInfo = res;
                // 到商城
                fnOpenWin({
                    name: 'shop_mall_win',
                    url: '../tabs/tab_shop.html',
                    slidBackEnabled: false,
                    reload: false,
                    animation: {
                        type: 'movein',
                        subType: 'from_bottom',
                        duration: 500
                    },
                    pageParam: {
                        submitPreview: params
                    }
                });
                api.sendEvent({
                    name: 'shop_order_buyAgin',
                    extra: {
                        submitPreview: params
                    }
                })
            }else {
                fnToast('商品已下架');
            }
        };
        MALLGET('single/oms/submitPreview', params, _callback);
    };
    fnAddCart(data.orderItemList, 0, callback)
}

// 再来一单加入购物车
function fnAddCart(goodsList, index, _callback) {
    var item = goodsList[index];
    var params = {
        'goodsId': item.productId,
        'skuId': item.productSkuId,
        'total': item.productQuantity,
        'buyRoad': '2'
    };
    var callback = function(data) {
        if(data && data.id) {
            _add_cart_id.push(data.id);
            if(++ index == goodsList.length) {
                // 全部加入购物车，进入订单预览
                _callback();
            }else {
                // 继续加入购物车
                fnAddCart(goodsList, index, _callback);
            }
        }else {
            fnToast('商品已下架');
        }
    };
    MALLGET('cart/addCart', params, callback);
}

// 重开发票
function fnOrderReInvoice(data) {
    fnOpenFrame({
        name: 'again_invoice',
        url: './again_invoice.html',
        pageParam: {
            order: data
        }
    })
}

// 去评价
function fnToComment(data) {
    fnOpenPublicWin('评价商品', 'teacher/assess', {
        // 订单 id
        orderId: data.id,
        // 商品列表
        orderItemList: data.orderItemList
    });
}